// app.js
const regeneratorRuntime = require('./lib/runtime');
const co = require('./lib/co');
const wx = require('./lib/wx');
const Api = require('./utils/api.js');
const wxapp = require('./lib/wxapp');

App({
  onLaunch: wxapp.handler(function* onLaunch(next) {
    // yield this.checkWxSession();

    yield next;
  }),

  checkWxSession: function* checkWxSession() {
    try {
      yield wx.checkSession();
    } catch (e) {
      yield this.wxLogin();
    }

    const openId = wx.getStorageSync('openId');
    const wxUserInfo = wx.getStorageSync('wxUserInfo');
    if (!openId || !wxUserInfo) {
      yield this.wxLogin();
    }
  },

  wxLogin: function* wxLogin() {
    const loginResponse = yield wx.login();
    if (loginResponse.code) {
      yield this.getSessionKey(loginResponse.code);
    }

    let wxUserInfo;
    try {
      wxUserInfo = yield wx.getUserInfo();
    } catch (err) {
      return;
    }

    if (wxUserInfo && wxUserInfo.userInfo) {
      wx.setStorageSync('wxUserInfo', wxUserInfo.userInfo);
    }
  },

  getSessionKey: function* getSessionKey(code) {
      var getSessionKey = Api.getSessionKey();
      var that = this;
      if(!wx.getStorageSync('auth_token_cache_key')) {
        wx.request({
          url: getSessionKey,
          header: {
            'content-type': 'application/x-www-form-urlencoded',
          },
          method: 'POST',
          data: {
            code: code
          },
          complete: function (res) {
            if (!res.data.status) {
              wx.setStorageSync('wxOpenID', res.data.openid);
              wx.setStorageSync('wxSessionKey', res.data.session_key);
              that.openidLogin();
            }
          }
        });
      }
  },
  openidLogin :function(){
    var login4OpenId = Api.login4OpenId();
    var that = this;
    wx.request({
      url: login4OpenId,
      header: {
        'content-type': 'application/x-www-form-urlencoded',
      },
      method: 'POST',
      data: {
        open_id: wx.getStorageSync('wxOpenID')
      },
      complete: function (res) {
        if (res.data.status) {
          // 将token存入缓存
          wx.setStorageSync('auth_token_cache_key', res.data.data);

          wx.showToast({
            title: '登录成功',
            icon: 'success',
            duration: 2000,
          });
          setTimeout(() => {
            wx.hideToast();
            that.goToMe();
          }, 3000);
        }
      }
    });
  },
  goToMe: function () {
    wx.reLaunch({ url: 'pages/me/me' });
    return ;
  }

});
// const app = getApp();
// wxapp.use(function* logininterceptor(next) {
//   try {
//     const pages = getCurrentPages();
//     const currentPage = pages && pages.length > 0 ? pages[pages.length - 1] : null;
//     const ignoreCheckLogin = currentPage ? currentPage.data.ignoreCheckLogin : null;
//     const user = wx.getStorageSync('user');
//     if (!ignoreCheckLogin && !user) {
//       yield app.wxLogin();
//     } else {
//       yield next;
//     }
//   } catch (error) {
//     if (error && error.name === 'LoginRequiredError') {
//       yield app.wxLogin();
//     } else {
//       throw error;
//     }
//   }
// });
